package com.wufun.overseas.adapters;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.download.UtilsMy;
import com.wufun.baselibrary.impl.AdapterInterface;
import com.wufun.baselibrary.net.HttpUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.main.activity.PostDetailsActivtiy;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.models.bean.GameDetailBean;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.rpc.RpcConstant;
import com.wufun.overseas.tools.DownloadManager;
import com.wufun.overseas.utils.AppDevicesUtil;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by yangg on 2017/12/4.
 */

public class GameDetailAdapter extends BaseAdapter {

    String btn_state;
    int state;
    Context mContent;
    int pro;
    String speed;
    List<GameDetailBean.DataBean.PostListBean> list = new ArrayList<>();
    private AdapterInterface mAdapterInterface;

    private boolean isReflash = false;

    public void setReflash() {
        isReflash = !isReflash;
        notifyDataSetChanged();
    }

    public void getSpeed(int progrerss, String speeds) {
        pro = progrerss;
        speed = speeds;
    }

    public GameDetailAdapter(Context content, AdapterInterface mAdapterInterface) {
        this.mContent = content;
        this.mAdapterInterface = mAdapterInterface;
    }

    public List<GameDetailBean.DataBean.PostListBean> getData() {

        return list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public int getViewTypeCount() {

        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        if (list.get(position).getDisplay_type() == 1) {
            return 0;
        } else if (list.get(position).getDisplay_type() == 3) {
            return 1;
        }
        return -1;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContent).inflate(R.layout.gamedetail_item, null);
            viewHolder.tv_titleRom = (TextView) convertView.findViewById(R.id.gamede_item_titleRom);
            viewHolder.tv_content = (TextView) convertView.findViewById(R.id.gamede_item_titleSecondRom);
            viewHolder.tv_gamename = (TextView) convertView.findViewById(R.id.gamede_item_GameName);
            viewHolder.tv_gamesize = (TextView) convertView.findViewById(R.id.gamede_item_gamesize);
            viewHolder.tv_address = (TextView) convertView.findViewById(R.id.gamede_item_address);
            viewHolder.tv_opensize = (TextView) convertView.findViewById(R.id.gamede_item_openSize);
            viewHolder.tv_like = (TextView) convertView.findViewById(R.id.gamede_item_up_like);
            viewHolder.tv_revelt = (TextView) convertView.findViewById(R.id.gamede_item_revert);
            viewHolder.iv_icon = (SimpleDraweeView) convertView.findViewById(R.id.gamede_item_img_home);
            viewHolder.tv_down = (TextView) convertView.findViewById(R.id.btn_download);
            viewHolder.down_ll = (LinearLayout) convertView.findViewById(R.id.btn_download_ll);
            viewHolder.tv_desc = (TextView) convertView.findViewById(R.id.tv_desc);
            viewHolder.ll_go_post = (LinearLayout) convertView.findViewById(R.id.ll_go_post);
            viewHolder.ll_desc = (LinearLayout) convertView.findViewById(R.id.ll_desc_size);    //未带进度条的
            viewHolder.ll_progress_bar = (LinearLayout) convertView.findViewById(R.id.ll_progress); //带进度条的
            viewHolder.tv_count = (TextView) convertView.findViewById(R.id.loadCount);
            viewHolder.tv_state = (TextView) convertView.findViewById(R.id.tv_state);
            viewHolder.pbar = convertView.findViewById(R.id.progressBar);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.tv_revelt.setText(list.get(position).getCommit() + "");
        viewHolder.tv_titleRom.setText(list.get(position).getSubject());
        viewHolder.tv_content.setText(list.get(position).getMessage());
        viewHolder.tv_address.setText(list.get(position).getFname());
        viewHolder.tv_opensize.setText(list.get(position).getView() + "");
        viewHolder.tv_like.setText(list.get(position).getPraise() + "");
        int type = getItemViewType(position);

        if (pro == 0) {
            DownLoadModel temp = DownloadManager.getInstance().getDownloadByUrl(list.get(position).getRelation_game().getGame_down_url_mote());
            if (DownloadManager.getInstance().getAllNotFinishDownload()==true){
                pro = temp.getProgress();
            }

        }
        if (type == 0) {
            if (list.get(position).getGoole_play() != null) {
                viewHolder.tv_down.setText("Google paly");
                viewHolder.iv_icon.setImageURI(list.get(position).getGoole_play().getIcon());
                viewHolder.tv_gamesize.setText(list.get(position).getGoole_play().getQuality());
                viewHolder.tv_gamename.setText(list.get(position).getGoole_play().getGame_name());
                viewHolder.tv_desc.setText(list.get(position).getGoole_play().getDescription());
            }


        } else if (type == 1) {
            viewHolder.tv_gamename.setText(list.get(position).getRelation_game().getGame_name());
            viewHolder.tv_gamesize.setText(list.get(position).getRelation_game().getGame_size() + "M");
            viewHolder.iv_icon.setImageURI(list.get(position).getRelation_game().getGame_ico_remote());
            viewHolder.tv_desc.setText(list.get(position).getRelation_game().getGame_desc());
            try {
                viewHolder.down_ll.setBackgroundResource(R.drawable.recom_blue_butn);
                viewHolder.tv_down.setTextColor(mContent.getResources().getColor(R.color.app_blue_color));
                state = DownloadManager.getInstance().getDownloadTaskStatus(list.get(position).getRelation_game().getGame_down_url_mote());
                if (state == CommonDownloadTask.STATUS_NOT)
                    state = list.get(position).getGame_state();
                String down_uri = list.get(position).getRelation_game().getGame_down_url_mote();
                if (down_uri != null && down_uri.indexOf(".apk") == -1) {
                    state = DownloadManager.getInstance().getDownloadTaskStatus(list.get(position).getRelation_game().getGame_down_url_mote());
                    switch (state) {
                        case CommonDownloadTask.STATUS_NOT:  //未下载
                        case CommonDownloadTask.STATUS_NORMAL:
                            btn_state = mContent.getResources().getString(R.string.download_status_start_str);
                            viewHolder.tv_state.setVisibility(View.GONE);
                            viewHolder.ll_progress_bar.setVisibility(View.GONE);
                            viewHolder.ll_desc.setVisibility(View.VISIBLE);
                            break;
                        case CommonDownloadTask.STATUS_START:   //downloading
                        case CommonDownloadTask.STATUS_PROGRESS:

                            viewHolder.ll_progress_bar.setVisibility(View.VISIBLE);
                            viewHolder.tv_state.setVisibility(View.VISIBLE);
                            viewHolder.ll_desc.setVisibility(View.GONE);

                            btn_state = mContent.getResources().getString(R.string.download_stop_str);
                            double size = Double.valueOf(list.get(position).getRelation_game().getGame_size());
                            size = size * 1024 * 1024;
                            double count=pro*size*100/10000;
                            long countsize = (long) count;
                            viewHolder.tv_count.setText(UtilsMy.FormatFileSize(countsize) + "/" + UtilsMy.FormatFileSize((long) (size)));
                            viewHolder.tv_state.setText(speed == null ? "0KB" : speed + "/s");
                            viewHolder.ll_progress_bar.setVisibility(View.VISIBLE);
                            viewHolder.ll_desc.setVisibility(View.GONE);
                            break;
                        case CommonDownloadTask.STATUS_FINISH:  //  play
                            btn_state = mContent.getResources().getString(R.string.download_status_open_str);
                            viewHolder.tv_state.setVisibility(View.GONE);
                            viewHolder.ll_progress_bar.setVisibility(View.GONE);
                            viewHolder.ll_desc.setVisibility(View.VISIBLE);
                            break;
                        case CommonDownloadTask.STATUS_STOP:  //stop
                            btn_state =  mContent.getResources().getString(R.string.download_status_goon_str);
                            viewHolder.tv_state.setText(mContent.getResources().getString(R.string.download_stop_str));
                            viewHolder.tv_state.setVisibility(View.VISIBLE);
                            viewHolder.ll_progress_bar.setVisibility(View.VISIBLE);
                            viewHolder.ll_desc.setVisibility(View.GONE);
                            break;
                        case CommonDownloadTask.STATUS_ERROR:  //error
                            viewHolder.tv_state.setVisibility(View.VISIBLE);
                            viewHolder.tv_state.setText(mContent.getResources().getString(R.string.download_fail_str));
                            btn_state = mContent.getResources().getString(R.string.download_status_re_str);
                            viewHolder.down_ll.setBackgroundResource(R.drawable.recom_orange_butn);
                            viewHolder.tv_down.setTextColor(mContent.getResources().getColor(R.color.app_main_color));
                            viewHolder.ll_progress_bar.setVisibility(View.VISIBLE);
                            viewHolder.ll_desc.setVisibility(View.GONE);
                            break;
                        case CommonDownloadTask.STATUS_ZIP_PROGRESS:  // unzip
                        case CommonDownloadTask.STATUS_STSRT_ZIP:
                            btn_state = mContent.getResources().getString(R.string.zip_str);
                            viewHolder.tv_state.setText(mContent.getResources().getString(R.string.zip_str));
                            viewHolder.tv_state.setVisibility(View.VISIBLE);
                            viewHolder.ll_progress_bar.setVisibility(View.GONE);
                            viewHolder.ll_desc.setVisibility(View.VISIBLE);
                            break;
                        case CommonDownloadTask.STATUS_ZIP_FAIL:  // unzip error
                            btn_state = mContent.getResources().getString(R.string.zip_fail_str);
                            viewHolder.tv_state.setVisibility(View.VISIBLE);
                            viewHolder.tv_state.setText(mContent.getResources().getString(R.string.zip_fail_str));
                            viewHolder.down_ll.setBackgroundResource(R.drawable.recom_orange_butn);
                            viewHolder.tv_down.setTextColor(mContent.getResources().getColor(R.color.app_main_color));
                            break;
                    }

                } else {
                    btn_state = "Download";
                    Log.e("TAG", "URI ERROR");
                }

            } catch (Exception e) {
                btn_state = "Download";
                e.printStackTrace();
            }
            viewHolder.tv_down.setText(btn_state);

            if (viewHolder.pbar.getVisibility() == View.VISIBLE)
                viewHolder.pbar.setProgress(pro);
        }


        viewHolder.ll_go_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContent, PostDetailsActivtiy.class);
                intent.putExtra("title", list.get(position).getSubject());
                intent.putExtra("Tid", list.get(position).getPid());
                intent.putExtra("type", 1);
                mContent.startActivity(intent);
            }
        });

        final ViewHolder finalViewHolder = viewHolder;
        final ViewHolder finalViewHolder1 = viewHolder;
        viewHolder.down_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list.get(position).getDisplay_type() == 1) {
                    //google play package_name
                    String google_package = "com.android.vending";
//                    launchAppDetail(list.get(position).getGoole_play().getPackage_name(), google_package);
                    AppDevicesUtil.launchAppDetail(list.get(position).getGoole_play().getPackage_name(), google_package, mContent);
                    PostNetDot(list.get(position).getGoole_play().getPackage_name(), position);
                } else if (list.get(position).getDisplay_type() == 3) {

                    if (state == 1 || state == 0 || state == -2 || state == 4||CommonDownloadTask.STATUS_STOP==state
                            ||CommonDownloadTask.STATUS_PROGRESS==state||CommonDownloadTask.STATUS_START==state) {
                        //下载中，或者暂停 这边不处理
                        mAdapterInterface.onAdapterItemClick(v, position);
                    }

                }
            }
        });


        return convertView;
    }

    private void PostNetDot(String Package_name, int po) {
        try {
            Map<String, String> map = new HashMap<String, String>();
            PackageManager pm = mContent.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContent.getPackageName(), 0);
            map.put("client", pi.packageName + pi.versionCode);
            map.put("device", Build.DEVICE);
            map.put("os", AppDevicesUtil.getOS());
            String ipadd = AppDevicesUtil.getIPAddress(mContent);
            map.put("link", list.get(po).getPid() + "");
            map.put("ip", ipadd);
            map.put("package_name", Package_name);
            HttpUtils.doPost(RpcConstant.forumRootUrl + "/forum/Google_middleware/main", map, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.e("TAG", "上传成功！");
                }
            });
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 启动到应用商店app详情界面
     *
     * @param appPkg    目标App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public void launchAppDetail(String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg) || TextUtils.isEmpty(marketPkg)) {
                Toast.makeText(mContent, "没有包名", Toast.LENGTH_SHORT).show();
                return;
            }
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContent.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ViewHolder {
        TextView tv_titleRom, tv_content, tv_gamename, tv_gamesize, tv_address, tv_opensize, tv_like, tv_revelt;
        SimpleDraweeView iv_icon;
        TextView tv_down;
        TextView tv_desc, tv_count, tv_state;
        ProgressBar pbar;
        LinearLayout down_ll, ll_go_post, ll_progress_bar, ll_desc;
    }
}
